import Vue from 'vue';
const that = new Vue();
const msgPlat = 1;
//Websocket业务信息类型
const BUSINESS_CODE = {
	ping: "WSHeartBeat", //'心跳',
	FriendBindChange: "FriendBindChange",
	DeleteFriend:"FriendDeleteNotify",
	launchGroup: "LaunchGroup", //'发起群聊',
	chatting: "Chatting", //'聊天信息',
	deleteGroup: 'DeleteGroup', //解散群组
	AI: "AI" ,//'AI'
	FriendCircle:'FriendCircle' ,//朋友圈动态
	Calling:'Calling'
}
//Websocket业务类型为chatting时群组聊天的信息类型
const MSG_TYPE = {
	SYSTEM_MSG: 0, //系统信息
	USER_MSG: 1, // 用户信息
}
//MSG_TYPE=0时，系统信息的具体类型
const SYS_MSG_TYPE = {
	updateGroupName: 'updateGroupName',//修改群名称
	updateGroupAvatar: 'updateGroupAvatar',//修改群头像
	updateGroupNotice: 'updateGroupNotice',//修改群公告
	quitGroup: 'quitGroup', //主动退出群组
	joinGroupMember: 'joinGroupMember',//添加、邀请群成员
	deleteGroupMember: 'deleteGroupMember',//删除群成员
	revertMessage:"revertMessage",//撤回信息
}
// 信息内容的类型  1-文本 2-图片 3-视频  4-语音信息 5-文件 6-其他
const CONTENT_TYPE = {
	/**文本信息*/
	TEXT_CONTENT_TYPE: 1,
	/**图片信息*/
	IMG_CONTENT_TYPE: 2,
	/**视频信息*/
	VIDEO_CONTENT_TYPE: 3,
	/**语音信息*/
	AUDIO_CONTENT_TYPE: 4,
	/**文件*/
	FILE_CONTENT_TYPE: 5,
	/**位置类型*/
	OTHER_CONTENT_TYPE: 6,
	/**红包信息*/
	RED_BAG_CONTENT_TYPE: 7,
	/**转账信息*/
	TRANSFER_CONTENT_TYPE: 13,
	/**名片信息*/
	FRIEND_INFO_CONTENT_TYPE: 8,
	/**位置信息*/
	LOCATION_CONTENT_TYPE: 9,
	/**合并聊天记录信息*/
	CHAT_RECORD_CONTENT_TYPE: 10,
	/**图文信息*/
	IMG_TEXT_COM_CONTENT_TYPE: 11,
	/**视频图文*/
	VIDEO_TEXT_COM_CONTENT_TYPE: 12
}

//下载图片资源至本地，返回文件的本地临时路径（废弃，没有调用）
function setImageLocalSrc(url, msgId) {
	if (url && msgId) {
		uni.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: function(res2) {
							uni.setStorageSync("image" + msgId, res2.savedFilePath)
						}
					});
				}
			}
		})
	}
}
//下载视频文件到本地缓存（废弃，没有调用）
function setVideoLocalSrc(url, msgId) {
	if (url && msgId) {
		let path = uni.getStorageSync("video" + msgId);
		if (path && path.length > 0) {
			//console.log("已经存在本地缓存，无需继续存储");
			return;
		}
		uni.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: function(res2) {
							//console.log("视频存入到本地缓存中===msgId==="+msgId,res2.savedFilePath)
							uni.setStorageSync("video" + msgId, res2.savedFilePath)
						}
					})
				}
			}
		})
	}
}
//将图片，视频信息放入缓存中（废弃，没有调用）
function saveLocal(messageObj) {
	let msgId = messageObj.id;
	let contentType = messageObj.contentType;
	let contentObj = messageObj.content;
	switch (contentType + '') {
		case "2":
			let url = contentObj.fullPath;
			let target = contentObj.fileSaveTarget;
			if (target == "local") {
				let fileName = contentObj.fileName;
				url= that.$u.api.multipartAddress.getFileByPath+url;
			}
			setImageLocalSrc(url, msgId);
			break;
		case "3":
			let screenShot = contentObj.screenShot;
			if (screenShot) {
				if (contentObj.fileSaveTarget == "local") {
					screenShot=that.$u.api.multipartAddress.getFileByPath+screenShot;
					let fileName = contentObj.fileName;
				}
				setImageLocalSrc(screenShot, msgId);
			}
			break;
		case "4":
			break;
		case "11":
			break;
		case "12":
			break;
		default:
			break;
	};
}
//更新服务端信息记录(修改聊天记录)（废弃，没有调用）
function updateServerMessageRecord(chatGroupId, newMessage, self) {
	let param = {
		groupId: chatGroupId,
		newMessage: newMessage
	};
	self.$u.api.groupMessage.updateServerMessageRecord(param).then(res => {
		if (res.code == 200) {
			console.log("==========服务端信息记录更新完成============");
		}
	});
}
//将用户头像缓存到本地（废弃，暂时没有调用）
function setUserAvatarLocalSrc(url, userId) {
	if (url && userId) {
		uni.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: function(res2) {
							uni.removeStorageSync("avatar" + userId);
							uni.setStorageSync("avatar" + userId, res2.savedFilePath)
						}
					});
				}
			}
		})
	}
}
//获取用户缓存的头像（废弃，暂时没有调用）
function getUserLocalAvatar(userId, self) {
	let localAvatar = uni.getStorageSync("avatar" + userId);
	return localAvatar;
}


//-------------------处理不同业务类型的websocket信息---------------------
//监听到AI信息
function handleAIMessage(messageObj,self){
	uni.$emit("handleAIMessage",messageObj);
}
//监听好友关系通知,新增好友通知,删除好友通知,拉黑好友通知
function handleContactMessage(messageObj,self){
	console.log("好友关系信息内容",messageObj);
	uni.$emit("handleContactMessage",messageObj);
	/* if(self.vuex_userInfo.id==messageObj.content.friendId){
		uni.$emit("handleContactMessage",messageObj);
	}; */
}	
//监听删除好友
function handleDelFriendMessage(messageObj,self){
	uni.$emit("handleContactMessage",messageObj);//刷新通讯录
	uni.$emit("updateGroupList",messageObj);//刷新群组列表
	let groupId= messageObj.content.chatGroupId;
	if(null!=groupId&&self.vuex_currentChatGroupId==groupId){
		uni.showModal({
			title: '提示',
			content: '哦吼~您已经被对方删除好友啦',
			showCancel:false,
			confirmColor:'#19be6b',
			complete:function(res){
				uni.reLaunch({
					url:'/pages/tabbar/group/group'
				}) 
			}
		});
	}
}	
	
//处理解散群组
function handleDeleteGroup(messageObj,self){
	let groupId= messageObj.chatGroupId;
	uni.$emit("updateGroupList",messageObj);
	if(self.vuex_currentChatGroupId==groupId){
		uni.showModal({
			title: '提示',
			content: '当前群组已经被解散!',
			showCancel:false,
			confirmColor:'#19be6b',
			complete:function(res){
				uni.switchTab({
					url:'/pages/tabbar/group/group'
				}) 
			}
		});
	}
}
//处理服务端发过来的聊天信息
function handleChatMsg(messageObj, self) {
	if (messageObj.userId == self.vuex_userInfo.id) {
		messageObj.meFlag = true;
	} else {
		messageObj.meFlag = false;
	};
	let groupId= messageObj.chatGroupId;
	//判断此信息是否拒收
	if (groupId.startsWith("SG")) {
		let content = messageObj.content;
		let receiveInfo = content.receiveInfo;
		//如果拒收者存在,且拒收人是自己,那就不处理
		if (null != receiveInfo && receiveInfo.receiveStatus == 3 && receiveInfo.refusedUser == self.vuex_userInfo.id) {
			console.log("此信息被我拒收,对方已被拉入黑名单");
			return;
		}
		if (null != receiveInfo && receiveInfo.receiveStatus == 3 && receiveInfo.refusedUser != self.vuex_userInfo.id) {
			content.refuseTips = "消息已发出,但被对方拒收!";
		}
	}
	let messageType = messageObj.messageType;
	//如果是系统信息
	if (messageType == MSG_TYPE.SYSTEM_MSG) {
		let content = messageObj.content;
		let sysMsgType = content.sysMsgType;
		//如果系统信息类型我主动退出群组,这里要将从群组列表中删除此群,以及清空群组信息记录
		if (sysMsgType == SYS_MSG_TYPE.quitGroup && messageObj.userId == self.vuex_userInfo.id) {
			let userId = self.vuex_userInfo.id;
			uni.$emit("updateGroupList", null);
			return;
		}
		//如果是删除群成员
		if (sysMsgType == SYS_MSG_TYPE.deleteGroupMember) {
			let currentUserId = self.vuex_userInfo.id;
			//如果删除的成员里面包含了我
			if (content.params && content.params.members && content.params.members.indexOf(currentUserId) != -1) {
				//群组列表中删除
				uni.$emit("updateGroupList", null);
				//如果正在此群中聊天，则提示他被删除
				if (self.vuex_currentChatGroupId == groupId) {
					uni.showModal({
						title: '提示',
						content: '您已经被剔除群组!',
						showCancel: false,
						confirmColor: '#007AFF',
						complete: function(res) {
							uni.switchTab({
								url: '/pages/tabbar/group/group'
							})
						}
					});
				}
				return;
			}
		}
		//如果是加入群成员
		if (sysMsgType == SYS_MSG_TYPE.joinMemeber) {
			let currentUserId = self.vuex_userInfo.id;
			if (content.params && content.params.members && content.params.members.indexOf(currentUserId) != -1) {
				uni.$emit("updateGroupList", null);
				return;
			}
		}
	}
	//此处要更新最后一条信息到群组列表
	uni.$emit("updateGroupList", messageObj);
	//如果用户在当前聊天窗口,需要回显
	if (self.vuex_currentChatGroupId) {
		if (groupId == self.vuex_currentChatGroupId) {
			uni.$emit("pushMessage", messageObj);
		}
	}
	if (messageObj.meFlag == false) {
		//信息提示音
		self.globalUtil.palyMsgTipSelected(self,groupId);
	}
}

function handleFriendCircleMessage(messageObj,self){
	console.log("朋友圈动态信息",messageObj);
	uni.$emit("handleFriendCircle",messageObj);
	if(self.vuex_userInfo.id!=messageObj.content.userId){
		
	};
}


function handleCallingMessage(messageObj,self){
	console.log("监听到音视频通话长连接信息",messageObj);
	if(self.vuex_userInfo.id!=messageObj.content.userId){
		
	};
}

module.exports = {
	//常量导出
	BUSINESS_CODE: BUSINESS_CODE,
	MSG_TYPE: MSG_TYPE,
	SYS_MSG_TYPE: SYS_MSG_TYPE,
	CONTENT_TYPE: CONTENT_TYPE,
	msgPlat: msgPlat,
	//方法导出
	setImageLocalSrc,
	saveLocal,
	setVideoLocalSrc,
	setUserAvatarLocalSrc,
	getUserLocalAvatar,
	handleAIMessage,
	handleContactMessage,
	handleDelFriendMessage,
	handleDeleteGroup,
	handleChatMsg,
	handleFriendCircleMessage,
	handleCallingMessage
}